package com.neuedu.servlet;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ChkcodeServlet
 */
@WebServlet("/ChkcodeServlet")
public class ChkcodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChkcodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
//		1、定义验证码底图宽高
		int width = 80;
		int height = 30;
		
//		2、创建验证码底图
		BufferedImage image= new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
//		3、取验证码底图的画笔，用来画底图、写验证码
		Graphics g = image.getGraphics();
		
//		4、设置画笔颜色
		g.setColor(Color.BLUE);
		
//		5、画黑色的验证码底图
		g.fillRect(0, 0, width, height);
		
//		6、底图创建完毕写回客户端，运行查看无误，则关闭该代码，因ImageIO.write操作应放到最后执行
//		ImageIO.write(image, "jpeg", response.getOutputStream());		
		
//		7、定义验证码集合
		String[] codes = {"0","1","2","3","4","5","6","7","8","9"};
		StringBuilder sb = new StringBuilder();
		Random r = new Random();
		
//		8、修改画笔颜色，准备往底图上写验证码
		g.setColor(Color.WHITE);
		
//		9、随机生成4位验证码，写入底图并存入字符串
		for(int i=0; i<4; i++) {
			int n = r.nextInt(10);
			String code = codes[n];
//			10、验证码写入底图
			g.drawString(code, 20*i, 15);
//			11、验证码存入字符串
			sb.append(code);
		}
		
//		12、验证码字符串写入session，即存到服务器端，备验证使用
		request.getSession().setAttribute("checkcode", sb.toString());
		
//		13、设置响应内容为图片
		response.setContentType("image/jpeg");	
		
//		14、设置http报头，不允许缓存
		response.setDateHeader("expires", 0);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		
//		15、验证码写入客户端
		ImageIO.write(image, "jpeg", response.getOutputStream());						
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
